package org.epidroid.epidroid.androsoul.ui.conversation;

import java.util.Iterator;

import org.epidroid.epidroid.R;
import org.epidroid.epidroid.androsoul.engine.AndroSoul;
import org.epidroid.epidroid.androsoul.engine.contacts.Location;
import org.epidroid.epidroid.androsoul.engine.contacts.NetsoulContact;
import org.epidroid.epidroid.androsoul.engine.service.IAndroSoulService;
import org.epidroid.epidroid.androsoul.engine.service.IAndroSoulServiceListener;
import org.epidroid.epidroid.androsoul.engine.utils.StringUtils;
import org.epidroid.epidroid.androsoul.ui.utils.PicturesDownloader;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.graphics.drawable.Drawable;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

public class LoginAlertDialog {
	IAndroSoulService _service = null;
	Activity _activity = null;

	PicturesDownloader _picDownloader = null;

	IAndroSoulServiceListener _listener = null;

	public LoginAlertDialog(IAndroSoulService service, Activity context) {
		_service = service;
		_activity = context;

	}

	private void createListener(final String contact, final View alertDialogView) {

		_listener = new IAndroSoulServiceListener() {

			@Override
			public void dataChanged(Message o) {
				Boolean found = false;
				switch (o.what) {
				case AndroSoul.LIST_USERS:
					// List user finished, if we did not found
					// the location, update the description
					if (!found)
						setContactDescription(contact, alertDialogView);
					break;
				case AndroSoul.CONTACT_WHO_RESULT:
					found = true;
					String login = o.getData().getString("login");
					if (login.equals(contact)) {
						Log.v(AndroSoul.LOGCAT,
								"Found location, update description");
						setContactDescription(contact, alertDialogView);
					}
					break;
				// TODO: handle when contact updates status
				}
			}
		};

		// Add a listener that would enable us to receive the list user result
		_service.addListener(_listener);
		Log.v(AndroSoul.LOGCAT, "created listener");
	}

	private void removeListener() {
		_service.removeListener(_listener);
		_listener = null;
	}

	private void launchPicDownload(final NetsoulContact contact,
			final View alertDialogView) {
		_picDownloader = new PicturesDownloader(_activity, contact);
		_picDownloader.set_onFinish(new Runnable() {

			@Override
			public void run() {
				// Try updating the image again
				setContactImage(contact, alertDialogView);
			}

		}, false);
		_picDownloader.start();
	}

	public void showContact(final String login) {
		Boolean exists = true;

		AlertDialog.Builder alert = new AlertDialog.Builder(_activity);
		alert.setTitle(login);
		LayoutInflater factory = LayoutInflater.from(_activity);
		final View alertDialogView = factory.inflate(
				R.layout.androsoul_show_contact, null);
		alert.setView(alertDialogView);

		NetsoulContact contact = _service.getContactFromName(login);
		if (contact == null) {
			exists = false;
			createListener(login, alertDialogView);
			contact = _service.addContact(login);
			_service.sendListUser(login);
			alert.setPositiveButton(R.string.addcontact,
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							_service.addContact(login, _service.getGroupsList()
									.get(0));
							removeListener();
						}
					});
		}

		if (!exists) {
			setContactDescriptionRetrieving(login, alertDialogView);
			launchPicDownload(contact, alertDialogView);
		} else {
			setContactDescription(login, alertDialogView);
		}
		setContactImage(contact, alertDialogView);

		alert.setNegativeButton(R.string.back, null);
		alert.show();

		alert.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				removeListener();
			}
		});

	}

	/**
	 * TODO: Factorise that with the popup in the contacts list
	 * 
	 * @param c
	 * @param alertDialogView
	 */
	private void setContactDescription(String login, View alertDialogView) {
		NetsoulContact c = _service.getContactFromName(login);

		if (c == null) {
			return;
		}

		TextView txt = (TextView) alertDialogView
				.findViewById(R.id.show_contact_content);

		if (c.getLocations().isEmpty()) {
			txt.setText(c.getName() + " " + _activity.getString(R.string.not_connected));
			return;
		}

		String content = "";
		if (c.getComment() != null)
			content = "�" + StringUtils.urlDecode(c.getComment()) + "�\n\n";

		content += "Locations:";
		Iterator<Location> it = c.locIterator();
		while (it.hasNext()) {
			Location l = it.next();
			content += "\n" + StringUtils.urlDecode(l.getBestLocation());
			content += " - " + l.getIp();
		}
		txt.setText(content);
	}

	private void setContactDescriptionRetrieving(String login,
			View alertDialogView) {
		NetsoulContact c = _service.getContactFromName(login);

		if (c == null) {
			return;
		}

		TextView txt = (TextView) alertDialogView
				.findViewById(R.id.show_contact_content);
		txt.setText(R.string.contact_location);
	}

	private void setContactImage(NetsoulContact c, View alertDialogView) {
		ImageView img = (ImageView) alertDialogView
				.findViewById(R.id.show_contact_image);
		Drawable tmp = c.getImage(_activity, false);
		if (tmp != null)
			img.setImageDrawable(tmp);
		else
			img.setImageResource(R.drawable.contact_picture_2);
	}
}
